import './config.css';
import {Label, Button, Spinner, RadioButton} from '@kintone/kintone-ui-component/esm/js';
import * as tyc from '../api/TianyanchaAPI';
import * as qcc from '../api/QichachaAPI';
import {TianyanchaConfig} from '../component/TianyanchaConfig';
import {QichachaConfig} from '../component/QichachaConfig';
import {ErrorHandler} from '../common/ErrorHandler';

((PLUGIN_ID) => {
  'use strict';

  let pluginConfig = kintone.plugin.app.getConfig(PLUGIN_ID);
  if (!pluginConfig) {
    pluginConfig = {};
  }

  let proxyConfig = kintone.plugin.app.getProxyConfig(tyc.BASE_URL, 'GET');
  if (!proxyConfig) {
    proxyConfig = {};
  }

  const spinner = new Spinner();
  document.getElementById('company_info_config').appendChild(spinner.render());

  const serverList = [tyc.SERVER, qcc.SERVER];

  const companyInfoApiServerDiv = document.getElementById('company_info_api_server');
  companyInfoApiServerDiv.appendChild(new Label({text: '选择API提供商', isRequired: true}).render());
  const apiServerRadioButton = new RadioButton({
    name: 'apiServer',
    items: serverList.map(server => ({label: server.NAME, value: server.ID})),
    value: 'apiServer' in pluginConfig ?
      (() => {
        for (let i = 0; i < serverList.length; i++) {
          if (serverList[i].ID === pluginConfig.apiServer) {
            return pluginConfig.apiServer;
          }
        }
        return serverList[0].ID;
      })() : serverList[0].ID
  });
  companyInfoApiServerDiv.appendChild(apiServerRadioButton.render());


  const companyInfoApiServerSettingDiv = document.getElementById('company_info_api_server_setting');

  const tianyanchaConfig = new TianyanchaConfig({pluginConfig, proxyConfig});
  const qichachaConfig = new QichachaConfig({pluginConfig, proxyConfig});

  companyInfoApiServerSettingDiv.appendChild(tianyanchaConfig.render());
  companyInfoApiServerSettingDiv.appendChild(qichachaConfig.render());

  const selectApiServer = (value) => {
    tianyanchaConfig.hide();
    qichachaConfig.hide();
    switch (value) {
      case tyc.SERVER.ID:
        tianyanchaConfig.show();
        break;
      case qcc.SERVER.ID:
        qichachaConfig.show();
    }
  };

  selectApiServer(apiServerRadioButton.getValue());
  apiServerRadioButton.on('change', (value) => {
    selectApiServer(value);
  });


  const saveButton = new Button({text: '保存', type: 'submit'});
  document.getElementById('company_info_button').appendChild(saveButton.render());

  spinner.show();
  const errorHandler = new ErrorHandler();
  KintoneConfigHelper.getFields().then(fields => {
    tianyanchaConfig.setValue(fields);
    qichachaConfig.setValue(fields);
    spinner.hide();

    saveButton.on('click', () => {
      const apiServer = apiServerRadioButton.getValue();
      let errorMessage = '';
      switch (apiServer) {
        case tyc.SERVER.ID:
          errorMessage = tianyanchaConfig.checkValue();
          if (errorMessage) {
            errorHandler.throwError(errorMessage, tyc.SERVER.NAME);
          }
          break;
        case qcc.SERVER.ID:
          errorMessage = qichachaConfig.checkValue();
          if (errorMessage) {
            errorHandler.throwError(errorMessage, qcc.SERVER.NAME);
          }
          break;
        default:
          errorHandler.throwError('请选择API提供商');
      }

      const tianyanchaNewConfigValue = tianyanchaConfig.buildNewConfigValue(apiServer);
      const qichachaNewConfigValue = qichachaConfig.buildNewConfigValue(apiServer);

      const newConfig = {
        apiServer,
        ...tianyanchaNewConfigValue,
        ...qichachaNewConfigValue
      };

      kintone.plugin.app.setConfig(newConfig, () => {
        kintone.plugin.app.setProxyConfig(
          tyc.BASE_URL,
          'GET',
          {'Authorization': tianyanchaConfig.getTokenValue()},
          {}
        );
      });
    });
  }).catch(e => {
    errorHandler.throwError(e);
  });
})(kintone.$PLUGIN_ID);